package newfragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.dell.avtivity.R;
import com.example.dell.avtivity.Register;
import com.example.dell.avtivity.Search;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import DealWithMd5.DealData;
import NetRequest.SendRuest;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.example.dell.avtivity.R.id.email;

/**
 * Created by dell on 2017/1/26.
 */

public class LoginFragment extends Fragment {

    private String TAG = "TAG";
    // UI references.
    private AutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;
    private String user＿login = "";
    private String password＿login = "";
    private View view = null;
    private View focusView = null;

    private final int LOGINSUCCESS = 1;
    private final int LOGINFAILED = 2;


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOGINSUCCESS:
                    Toast.makeText(view.getContext(), "成功登陆", Toast.LENGTH_SHORT).show();
                    mProgressView.setVisibility(View.GONE);

                    break;
                case LOGINFAILED:
                    Toast.makeText(view.getContext(), "登陆失败", Toast.LENGTH_SHORT).show();
                    showProgress(false);
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_login, container, false);
        mLoginFormView = view.findViewById(R.id.login_form);
        mProgressView = view.findViewById(R.id.login_progress);
        mEmailView = (AutoCompleteTextView) view.findViewById(email);
        mPasswordView = (EditText) view.findViewById(R.id.password);
        final RegisterFragment registerFragment = new RegisterFragment();
        /*
        登录事件
         */
        final Button LoginButton = (Button) view.findViewById(R.id.email_sign_in_button);
        LoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (attemptLogin() == 2) {
                    String username = mEmailView.getText().toString();
                    String password_ = mPasswordView.getText().toString();
                    String password = DealData.getMd5(password_);

                    SendRuest sr = new SendRuest(view.getContext());
                    sr.SendRequest_LoginWithUserName(username, password, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.d(TAG, "LOGIN RESPONSE error");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String responsedata = response.body().string();
                            try {
                                JSONObject jo = new JSONObject(responsedata);
                                String status = jo.getString("error_code");
                                if (status.equals("0")) {
                                    Message msg = new Message();
                                    msg.what = LOGINSUCCESS;
                                    handler.sendMessage(msg);
                                } else {
                                    Message msg = new Message();
                                    msg.what = LOGINFAILED;
                                    handler.sendMessage(msg);
                                }
                            } catch (JSONException e) {
                                Message msg = new Message();
                                msg.what = LOGINFAILED;
                                handler.sendMessage(msg);
                                e.printStackTrace();
                            }
                        }
                    });
                    mProgressView.setVisibility(View.GONE);
                }
            }
        });

        /*
        注册事件
         */
        Button register = (Button) view.findViewById(R.id.register_login);
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getContext(), Register.class);
                startActivity(intent);
            }
        });


        /**
         * test
         */
        Button testbtn = (Button) view.findViewById(R.id.testbtn);
        testbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getContext(), Search.class);
                startActivity(intent);
            }
        });


        return view;
    }

    private int attemptLogin() {

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        user＿login = mEmailView.getText().toString();
        password＿login = mPasswordView.getText().toString();

        int cancel = 0;

        // Check for a valid password, if the user entered one.
        if (TextUtils.isEmpty(password＿login) || isPasswordValid(password＿login)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = 1;
        }

        if (TextUtils.isEmpty(user＿login)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = 1;
        }
        if (cancel == 1) {
            focusView.requestFocus();

        } else {
            showProgress(true);
            cancel = 2;
        }
        return cancel;
    }

    /*
    验证用户名格式
     */
    private boolean isUserValid(String user) {
        return true;
    }

    /*
    验证密码长度
     */
    private boolean isPasswordValid(String password) {

        return password.length() < 4;
    }

    /*
      显示进度条
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
//                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }


}
